package com.heo.redis.impl;

import java.io.Serializable;
import java.util.Map;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heo.pojo.ControlInfoEntity;
import com.heo.pub.DictEnum;
import com.heo.redis.MyExpiredMessageDelegate;
import com.heo.util.HttpHelper;
import com.heo.util.RedisUtil;

public class MyExpiredMessageDelegateImpl implements MyExpiredMessageDelegate {

	private static Logger log = Logger.getLogger(MyExpiredMessageDelegateImpl.class);

	@Override
	public void handleMessage(String message) {
		log.info("String = " + message);
	}

	@Override
	public void handleMessage(Map message) {
		log.info("Map = " + message);
	}

	@Override
	public void handleMessage(byte[] message) {
		log.info("byte = " + message);
	}

	@Override
	public void handleMessage(Serializable message) {
		String meskey = message.toString();
		log.info("MyExpiredMessageDelegateImpl = " + meskey);
		if (meskey.startsWith(DictEnum.RedisKey.ORDER)) {
			meskey = meskey.replace(DictEnum.RedisKey.ORDER, DictEnum.RedisKey.ORDER_RESEND);
			String keyValue = (String) RedisUtil.getValue(meskey);
			if (keyValue != null) {
				RedisUtil.remove(meskey);
				JSONObject param = JSONObject.parseObject(keyValue);
				// 去redis里找设备的控制信息
				Object redisObj = RedisUtil.getValue(DictEnum.RedisKey.DEVICE_CONTROL + param.getString("appId") + ":"
						+ param.getString("deviceIMEI"));
				if (redisObj == null) {
					log.error("[启动设备]设备离线");
					return;
				}
				ControlInfoEntity controlInfo = (ControlInfoEntity) JSON.parseObject(redisObj.toString(),
						ControlInfoEntity.class);
				// 如果设备在redis里的信息不为null，那么就需要查询这个设备的通道的当前的状态
				Byte currStatus = controlInfo.getChannelStatus(param.getInteger("deviceChannelIndex"));
				if (currStatus == null) {
					log.error("[启动设备]启动设备错误，当前设备在redis里的信息不存在。可能已经离线，也可能设备的通道号不存在。");
					return;
				}
				if (currStatus != DictEnum.DeviceChannelStatus.FREE) {
					if (param.getInteger("appendCommand") == DictEnum.AppendCommand.DISABLE) {
						log.debug("[启动设备]已经工作中");
						return;
					}
				}
				String url = param.getString("url");
				param.remove("url");
				param.remove("appendCommand");
				HttpHelper.sendHttpPost(url, param.toJSONString());

			}
		}
	}

	@Override
	public void handleMessage(Serializable message, String channel) {
		System.out.println("Serializable = " + message + ",channel=" + channel);
		handleMessage(message);
	}

}
